﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Upreader.Usenet.Nntp.Encodings
{
    class MetaLine
    {
        private readonly byte[] _recognizablePrefix;
        private readonly int _maxRecognizablePrefixOffset;
        private int _nextRecognizablePrefixOffset;        

        public MetaLine(byte[] recognizablePrefix)
        {
            if (recognizablePrefix == null)
                throw new ArgumentNullException("recognizablePrefix");

            _recognizablePrefix = recognizablePrefix;
            _maxRecognizablePrefixOffset = recognizablePrefix.Length - 1;
        }

        public bool MoveNext(byte current)
        {
            byte intended = _recognizablePrefix[_nextRecognizablePrefixOffset];
            bool isMatch = current == intended;

            if (isMatch)
            {
                // increase the offset
                _nextRecognizablePrefixOffset++;

                // if were done, reset and raise the event
                if (_nextRecognizablePrefixOffset == _maxRecognizablePrefixOffset)
                {
                    Reset();
                    OnMetaLinePrefixHit(EventArgs.Empty);
                }
            }
            else
            {
                // no hit for us
                Reset();
            }

            return isMatch;
        }

        private void OnMetaLinePrefixHit(EventArgs e)
        {
            EventHandler handler = MetaLinePrefixHit;
            if (handler != null)
                handler(this, e);
        }

        public void Reset()
        {
            _nextRecognizablePrefixOffset = 0;
        }

        public event EventHandler MetaLinePrefixHit;
    }
}
